from docx import Document
from docxtpl import DocxTemplate
import re
import threading
from pubsub import pub

from ParseFormula import ParseFormula
from ParseGauge import ParseGauge

class ParseDocx:
    def __init__(self, path, mainframe, expath):
        self.DocTpl = DocxTemplate(path)
        self.Doc = Document(path)
        self.MainFrame = mainframe
        self.ThisParse = ParseFormula(self.MainFrame)
        self.End = False
        self.Pattern = '{{ .*? }}'
        self.Gauge = ParseGauge(self.MainFrame, '解析进度')
        # 多线程
        pub.subscribe(self.GaugeUpdate, "GaugeUpdate")
        self.Threading_1 = threading.Thread(target=self.Parse, args=())
        self.Threading_1.start()
        self.GaugeFun()
        print('ok 1')
        self.Threading_1.join()
        print('ok 2')
        self.Save(expath)
        print('ok 3')

    def Parse(self):
        context = dict()
        keys = set()
        # 正文
        for p in self.Doc.paragraphs:
            temp = re.findall(self.Pattern, p.text)
            if len(temp) > 0:
                for i in temp:
                    keys.add(i)

        # 表格
        for t in self.Doc.tables:
            for row in t.rows:
                for cell in row.cells:
                    for p in cell.paragraphs:
                        temp = re.findall(self.Pattern, p.text)
                        if len(temp) > 0:
                            for i in temp:
                                keys.add(i)
        
        # 页眉页脚
        for s in self.Doc.sections:
            for p in s.header.paragraphs:
                temp = re.findall(self.Pattern, p.text)
                if len(temp) > 0:
                    for i in temp:
                        keys.add(i)
            for p in s.footer.paragraphs:
                temp = re.findall(self.Pattern, p.text)
                if len(temp) > 0:
                    for i in temp:
                        keys.add(i)

        self.keys = keys
        

        for index, k in enumerate(keys):
            if '建筑安装工程费' in k or '销项税额' in k:
                k = k.replace('建筑安装工程费·除税价', '建筑安装工程费(除税价)')
                k = k.replace('建筑安装工程费·含税价', '建筑安装工程费(含税价)')
                k = k.replace('销项税额·折后', '销项税额(折后)')
            text = self.ThisParse.FormulaToList(k)[0]
            k = k.replace('(', '·')
            k = k.replace(')', '')
            context[k[3:-3]] = str(text)
            pub.sendMessage("GaugeUpdate", value=index, text=k)
        print('for index, k in enumerate(keys):')
        self.DocTpl.render(context)
        print('self.DocTpl.render(context)')
        self.End = True
        print('self.End = True')
        pub.sendMessage("GaugeUpdate", value=index+1, text=k)
        print('prase ok')

    def GaugeFun(self):
        self.Gauge.SetRange(1)
        self.Gauge.ShowModal()
        self.Gauge.SetValue(0)
        self.Gauge.SetLabel('正在读取word', 'all')
    
    def GaugeUpdate(self, value, text):
        self.Gauge.SetRange(len(self.keys))
        self.Gauge.SetValue(value)
        self.Gauge.SetLabel(text)
        if self.End:
            self.Gauge.SetLabel('已完成解析请点击完成导出', 'all')

    def Save(self, path):
        self.DocTpl.save(path)
